import axios from 'axios'
import { message } from 'antd'

const request = axios.create({
  baseURL: 'http://localhost:8888',
  timeout: 60000,
})

const loginOutCode = [401, 402]

function errorFun () {
  message.error('网络连接异常')
  return Promise.reject()
}

request.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token')
  if (token) {
    config.headers.token = token
  }
  return config
}, errorFun)

request.interceptors.response.use((response) => {
  const { data } = response
  if (data?.code === 1000) {
    return Promise.resolve(data)
  }
  if (data && loginOutCode.includes(data.code)) {
    message.error(data.message || '登录信息失效')
    window.loginOut()
    return Promise.reject(data)
  }
  message.error(data.message || '请求失败')
  return Promise.reject(data)
}, errorFun)

request.CancelToken = axios.CancelToken


export default request

